package cn.fl.ass.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.upload.api.IUploadApiService;
import cmm.comm.facade.upload.condition.SysUlDatCfgQueryCondition;
import cmm.comm.facade.upload.dto.SysUlDatCfgDTO;
import cmm.comm.facade.upload.dto.SysUlDatCfgDtlDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.condition.SysUsrQueryCondition;
import cmm.user.facade.system.dto.SysUsrDTO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.ass.service.IAssDealSellCostService;
import cn.fl.ass.vo.AssDealSellCostVO;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.condition.PrjFileInfoQueryCondition;
import cn.fl.project.vo.PrjFileInfoVO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.upload.constant.UploadConstant;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import fl.ass.facade.condition.AssDealSellCostQC;

/**
 * @Description: 处置-变卖费用信息表 控制层
 */
@Controller
@RequestMapping("/ass/assDealSellCost")
public class AssDealSellCostController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(AssDealSellCostController.class);

	/**
	 * AssDealSellCost 服务层BEAN
	 */
	@Autowired
	private IAssDealSellCostService assDealSellCostService;
	
	@Autowired
	private ISysUsrApiService sysUsrApiService;
	
	@Autowired
	private IUploadApiService uploadApiService;
	
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	
	@Autowired
	private ISysUlFilesRecService sysUlFilesRecService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("ass/assDealSellCost/list");
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("ass/assDealSellCost/modify");
		view.addObject("id", id);
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String tcDetailId = request.getParameter("tcDetailId");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		AssDealSellCostQC qc = new AssDealSellCostQC();
		if (StringUtils.isNotEmpty(tcDetailId)) {
			qc.setTcDetailId(Long.valueOf(tcDetailId));
		}
		page.setCondition(qc);

		Pager pager = this.assDealSellCostService.searchListPage(page);
		List<AssDealSellCostVO> list = (List<AssDealSellCostVO>) pager.getResultList();
		if(CollectionUtils.isNotEmpty(list)){
			List<Long> crtUsrIdList = new ArrayList<Long>();
			for (AssDealSellCostVO assDealSellCostVO : list) {
				if(assDealSellCostVO.getCrtUsrId()!=null && !crtUsrIdList.contains(assDealSellCostVO.getCrtUsrId()))
				crtUsrIdList.add(assDealSellCostVO.getCrtUsrId());
			}
			SysUsrQueryCondition sysUsrQC = new SysUsrQueryCondition();
			sysUsrQC.setUsrIds(crtUsrIdList);
			sysUsrQC.setSysCd(CurrentThreadContext.getCurrentSysCd());
			List<SysUsrDTO> sysUsrDTOList = this.sysUsrApiService.searchSysUsrList(sysUsrQC);
			if(CollectionUtils.isNotEmpty(sysUsrDTOList)){
				for (AssDealSellCostVO assDealSellCostVO : list) {
					for (SysUsrDTO sysUsrDTO : sysUsrDTOList) {
						if(null!=sysUsrDTO && null!=assDealSellCostVO && null!=sysUsrDTO.getId()
								&& sysUsrDTO.getId().equals(assDealSellCostVO.getCrtUsrId())){
							assDealSellCostVO.setCrtUsrIdNm(sysUsrDTO.getRefRlNm());
						}
					}
				}
			}
		}
		
		ListPageVO<AssDealSellCostVO> listPage = new ListPageVO<AssDealSellCostVO>(list, pager.getTotalCount());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.assDealSellCostService.removeById(Long.valueOf(id));
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		
		try {
			AssDealSellCostVO vo = this.assDealSellCostService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
			}
			result.setData(vo);
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newLogger("AssDealSellCostController 获取失败").setThrowable(ex).setKeys("id:" + id).info();
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.newLogger("AssDealSellCostController 获取失败").setThrowable(ex).setKeys("id:" + id).info();
		}
		return result;
	}

	/**
	 * 保存杂费信息
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		List<AssDealSellCostVO> voList = new ArrayList<AssDealSellCostVO>();
		try {
			voList = this.getRequestParam(request);
			boolean success = this.assDealSellCostService.batchAdd(voList);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
				return result;
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newLogger("AssDealSellCostController 保存杂费信息失败").setThrowable(ex).setKeys("voList:" + JSONObject.toJSONString(voList)).info();
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.newLogger("AssDealSellCostController 保存杂费信息失败").setThrowable(ex).setKeys("voList:" + JSONObject.toJSONString(voList)).info();
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		AssDealSellCostVO entity = null;
		try {
			entity = new AssDealSellCostVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			boolean success = this.assDealSellCostService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
            BaseLogUtils.newLogger("AssDealSellCostController 修改失败").setThrowable(ex).setKeys("entity:" + JSONObject.toJSONString(entity)).info();
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.newLogger("AssDealSellCostController 修改失败").setThrowable(ex).setKeys("entity:" + JSONObject.toJSONString(entity)).info();
		}
		return result;
	}
	
	/**
	 * 获取参数信息
	 * @param request
	 * @return
	 * @throws BaseException
	 */
	private List<AssDealSellCostVO> getRequestParam(HttpServletRequest request)throws BaseException{
		
		List<AssDealSellCostVO> assDealSellCostVOList = new ArrayList<AssDealSellCostVO>();
		
		String tcDetailId = request.getParameter("tcDetailId");//拖车信息明细ID
		if(StringUtils.isEmpty(tcDetailId)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "拖车信息明细ID不能为空.");
		}
		String costGridJSON = request.getParameter("costGridJSON");
		if(StringUtils.isNotEmpty(costGridJSON)){
			assDealSellCostVOList = JSON.parseArray(costGridJSON, AssDealSellCostVO.class);
		}
		if(CollectionUtils.isEmpty(assDealSellCostVOList)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "杂费信息为空.");
		}
		
		for (AssDealSellCostVO assDealSellCostVO : assDealSellCostVOList) {
			if(StringUtils.isEmpty(assDealSellCostVO.getCostMainCd())){
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "费用大类不能为空.");
			}
			if(StringUtils.isEmpty(assDealSellCostVO.getCostSubCd())){
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "费用小类不能为空.");
			}
			if(null==assDealSellCostVO.getCostAmtDouble()){
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "费用金额不能为空.");
			}
			if(StringUtils.isEmpty(assDealSellCostVO.getCostRem())){
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "费用说明不能为空.");
			}
			assDealSellCostVO.setDetailId(Long.valueOf(tcDetailId));
			assDealSellCostVO.setCostAmt(DecimalUtils.convertYuanToFen(assDealSellCostVO.getCostAmtDouble()));
			assDealSellCostVO.setIsDel(BaseConstant.IS_YESNO_NO);
			if(StringUtils.isEmpty(assDealSellCostVO.getId())){
				assDealSellCostVO.setCrtTm(new Date());
				assDealSellCostVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			}else{
				assDealSellCostVO.setMdfTm(new Date());
				assDealSellCostVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			}
		}
		
		return assDealSellCostVOList;
	}
	
	/**
     * 初始化资料列表
     */
    @RequestMapping(value = "/initFileInfoList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initFileInfoList(HttpServletRequest request, HttpServletResponse response) {
    	String dataId = request.getParameter("dataId");
    	String cfgCd = request.getParameter("cfgCd");
    	PrjFileInfoQueryCondition qc = new PrjFileInfoQueryCondition();
    	if(StringUtils.isNotEmpty(dataId)){
    		qc.setDataId(Long.valueOf(dataId));
    	}
    	if(StringUtils.isNotEmpty(cfgCd)){
    		qc.setCfgCd(cfgCd);
    	}
    	List<PrjFileInfoVO> list = this.getUploadFileList(qc);
    	if (CollectionUtils.isNotEmpty(list)) {
    		return new ListPageVO<PrjFileInfoVO>(list, list.size());
    	}
    	return new ListPageVO<PrjFileInfoVO>(new ArrayList<PrjFileInfoVO>(), 0);
    }
	/**
	 * 查询资料
	 * @param condition
	 * @return
	 * @throws BaseException
	 */
	private List<PrjFileInfoVO> getUploadFileList(PrjFileInfoQueryCondition condition) throws BaseException {
        //查询资料配置，系统代码,组织架构代码,配置编号 ,业务主键
        SysUlDatCfgQueryCondition ulDatCfgQueryCondition = new SysUlDatCfgQueryCondition();
        ulDatCfgQueryCondition.setSysCd(CurrentThreadContext.getCurrentSysCd());//系统代码
        if(StringUtils.isNotEmpty(condition.getCstMgrOrgCd())){
        	ulDatCfgQueryCondition.setOrgCd(condition.getCstMgrOrgCd());//客户经理组织架构代码
        }else{
        	ulDatCfgQueryCondition.setOrgCd(CapitalConstant.SYSORG);
        }
        
        ulDatCfgQueryCondition.setDataId(String.valueOf(condition.getDataId()));//业务主键
        List<String> cfgCdList = new ArrayList<>();
        cfgCdList.add(condition.getCfgCd());//配置编号
        ulDatCfgQueryCondition.setCfgCdList(cfgCdList);//配置编号集合
        List<SysUlDatCfgDTO> list = uploadApiService.searchSysUlDatCfgListByDataId(ulDatCfgQueryCondition);
        List<PrjFileInfoVO> voList = null;
        if (CollectionUtils.isNotEmpty(list)) {
            Map<String, String> audStsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), CapitalConstant.CODE_MATE_AUD_STS_CD);
            voList = new ArrayList<>();
            PrjFileInfoVO vo;
            //设置路径
            String picServicePath = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_SERVER_PATH);
            for (SysUlDatCfgDTO dto : list) {
                for (SysUlDatCfgDtlDTO dtlDTO : dto.getSysUlDatCfgDtlDTOList()) {
                    vo = new PrjFileInfoVO();
                    vo.setId(condition.getDataId());//业务主键
                    vo.setCfgDtlCd(dtlDTO.getCfgDtlCd());//配置子编号
                    vo.setDatNm(dtlDTO.getDatNm());//配置名称
                    vo.setCfgCd(dtlDTO.getCfgCd());//配置编号
                    vo.setOrgCd(dtlDTO.getOrgCd());//配置组织架构代码
                    vo.setCfgNm(dto.getCfgNm());//配置子名称
                    vo.setFileId(dtlDTO.getRecId());//附件ID
                    //如果有HTTP开头说明是可以访问路径,无需干涉
                    if(StringUtils.isNotBlank(dtlDTO.getFilePath()) && !dtlDTO.getFilePath().startsWith("http") && StringUtils.isNotBlank(picServicePath)){
                        vo.setFilePath(picServicePath+dtlDTO.getFilePath());
                    }else{
                        vo.setFilePath(dtlDTO.getFilePath());
                    }
                    vo.setFileNm(dtlDTO.getRecFileNm());//上传名称
                    vo.setCrtTm(dtlDTO.getRecCrtTm());//上传时间
                    vo.setIsMust(dtlDTO.getIsMust());//是否必传
                    if (StringUtils.isNotBlank(dtlDTO.getRecAudStsCd())) {
                        vo.setAudStsCd(dtlDTO.getRecAudStsCd());//验证状态
                    } else {
                        vo.setAudStsCd("0");//验证状态
                    }

                    if (audStsCdMap != null && audStsCdMap.containsKey(vo.getAudStsCd())) {
                        vo.setAudStsCdNm(audStsCdMap.get(vo.getAudStsCd()));
                    }
                    voList.add(vo);
                }
            }
        }
        return voList;
    }
	
	@RequestMapping(value = "/uploadFile.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object uploadFile(HttpServletRequest request, HttpServletResponse response) throws BaseException {
    	DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_FILE_UPLOAD_SUCC);
    	String fileParams = request.getParameter("fileParams");
    	String cfgCd = request.getParameter("cfgCd");
    	String cfgDtlCd = request.getParameter("cfgDtlCd");
    	String orgCd = request.getParameter("orgCd");
    	String dataId = request.getParameter("dataId");
    	String tabNm = request.getParameter("tabNm");
    	if (StringUtils.isBlank(dataId)) {
    		result.setSuccess(BaseConstant.IS_YESNO_NO);
    		result.setInfo(SysLogConstant.LOG_FILE_UPLOAD_FAIL);
    	} else {
    		boolean flag = this.sysUlFilesRecService.addAttchmnt(dataId, fileParams, cfgCd, cfgDtlCd, tabNm, null, null, null, false, orgCd);
    		if (!flag) {
    		    BaseLogUtils.newLogger("上传资料文件失败").setKeys("dataId:" + dataId, "cfgCd:" + cfgCd, "cfgDtlCd:" + cfgDtlCd, "file:" + JSON.toJSONString(fileParams)).info();
    			result.setSuccess(BaseConstant.IS_YESNO_NO);
    			result.setInfo(SysLogConstant.LOG_FILE_UPLOAD_FAIL);
    			return result;
    		}
    		BaseLogUtils.newLogger("上传资料文件成功").setKeys("dataId:" + dataId, "cfgCd:" + cfgCd, "cfgDtlCd:" + cfgDtlCd).info();
    	}
    	return result;
    }

}

